package com.emip.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.emip.bean.ValleyBean;
import com.emip.dao.BaseDAO;
import com.emip.dao.ValleyDAO;

@Repository("valleyDAO")
public class ValleyDAOImpl extends BaseDAO implements ValleyDAO {

	public int add(ValleyBean entity) {
		Integer id = (Integer)this.getHibernateTemplate().save(entity);
		return id.intValue();
	}

	public ValleyBean findByID(Integer ID) {
		ValleyBean bean = this.getHibernateTemplate().get(ValleyBean.class, ID);
		return bean;
	}

	public List<ValleyBean> getAll() {
		List<ValleyBean> result = this.getHibernateTemplate().find("from ValleyBean m order by ID");
		return result;
	}

	public void remove(ValleyBean entity) {
		this.getHibernateTemplate().delete(entity);
	}

	public void update(ValleyBean entity) {
		this.getHibernateTemplate().update(entity);
	}

	public Boolean findExist(ValleyBean entity) {
		Object[] params = new Object[] {entity.getName(), entity.getWaterSystem(), entity.getAlongSide()};
		List<ValleyBean> result = this.getHibernateTemplate().find("from ValleyBean m where name=? and waterSystem=? and alongSide=?", params);
		if (result.size()==0) {
			return false;
		}
		else {
			//是否存在的那条记录的name, waterSystem 和 alongSide 和自己是相同的，如果是的话，那么其实是update其他字段的一种操作，也是合法操作
			if (entity.getId()==0) {  //新增的情况
				return true;
			} else {
				ValleyBean eBean = this.getHibernateTemplate().get(ValleyBean.class, entity.getId());
				if (entity.getName().equals(eBean.getName()) &&
						entity.getWaterSystem().equals(eBean.getWaterSystem()) &&
						entity.getAlongSide().equals(eBean.getAlongSide())) {
					return false;
				} else {
					return true;
				}
			}
		}
	}

}
